/**
 * Created by Administrator on 2018/1/11.
 */

load("js/luaclient.js");

var v4_shanghai_java_funcs = {

    openHomePage : function(){
        logger.info("ShangHai taskKey={}判断当前代理是否可用{}",context.get(LUA_TASK_KEY),context.get(LUA_TASK_PROXY));
        var loginUrl="https://ebanks.bankofshanghai.com/pweb/prelogin.do?LoginType=R&_locale=zh_CN";
        var currentHtml=get(loginUrl);
        storeDataToFile(context,currentHtml, "loginHtml.html");
    },

    checkTargetWebsiteAvailable: function(){
        return true;

    },

    checkControlAvailable: function () {
        return luaFuncs.checkControlAvailable();
    },

    //检查代理是否可用
    checkProxyAvailable: function () {
        exitPluginProcess()
        var checkProxyRight = function () {
            return is_exist_by_id("LoginIdOrAc");
        }
        var getProxyErrorMsg = function () {
            return "代理ip异常";
        }
        return assertTrueOrThrowException("", checkProxyRight, getProxyErrorMsg)
    },
    login:function () {

        inputBaseSH();
        inputImgSH();
        inputSmsSH();
    },
    needRefreshHomePageOrNot : function() {
        // return equals(context.get("currentErrorCode"), BALO_99602_50)
        return false;
    },

    needResetEnvironment:function(){
        return true;
    },
    //抓取过程
    crawl: function () {
        crawlSH();
    },
    exitLogin: function () {
    },
    exit:function () {
    },
    releaseResources :function () {}

}

/**
 * --------------------业务抓取方法-----------------------
 * -----------------------start--------------------------
 */

function exitPluginProcess() {
    var taskkey=context.get(LUA_TASK_KEY);
    logger.info("SHBank taskKey={}，上海银行登陆前退出不必要的上海银行控件",taskkey)
    luaFuncs.exitPulignProcess()
}



var payMentDate;//还款日
var billDate;

var depositBillNum=1;//借记卡的账单
var billDetailNum=1;

var  usdCreditLimitInfoMap=new LinkedHashMap();//从基本信息页面存储美元相关信息
var basicInfoUsdBalance="basicInfoUsdBalance";//固定取信用卡美元可用额度
var basicInfoUsdCreditLimit="basicInfoUsdCreditLimit";//固定取信用卡美元信用额度
var basicInfoUsdCashLimit="basicInfoUsdCashLimit";//固定取信用卡美元现金可以额度

var creditCardNum=1; //信用卡的第n张卡
var times=0;//表示inputbase的次数

function inputBaseSH() {

    var loginResult = {}
    var loginFunc = function (loginResult) {
        var taskkey=context.get(LUA_TASK_KEY);
        var username=getLoginParams(context)[0];
        var password=context.get(LUA_TASK_TOKEN);
        logger.info("shbank taskKey=" + taskkey + " 用户名和密码登录输入");
        luaFuncs.setSizeAndShow();
        var inputResult = luaFuncs.inputUPAndGetOperationResult(username,password);
        hide();
        return inputResult;

    }
    var getLoginErrorMsgFunc = function (loginResult) {
        return "密码因控件输入错误"
    }
    return assertTrueOrThrowException(loginResult, loginFunc, getLoginErrorMsgFunc)
}



function inputImgSH()  {

    var imgResult = {}
    var taskkey=context.get(LUA_TASK_KEY);
    logger.info("Lua获取验证码图片");
    var validateImPath = get_image_by_id("form2_tokenImg");
    var stauts="";
    if(validateImPath!='path fail'){
        logger.info("使用人工打码平台获取验证码");
        context.put(TASK_IMG_PATH, validateImPath);
        context.put(TASK_IMG_REGEX,"[0-9a-zA-Z]{4}");
        var captchaResult = waitImgCodeBySecondsByJs(context,120,true,3);


        logger.info("验证码 路径 {},结果{}", validateImPath, captchaResult);
        set_input_text_by_id("_vToken1", captchaResult);
         stauts =luaFuncs.loginAndCheck("btnLogin2");
    }else{
         stauts=luaFuncs.loginAndCheck("btnLogin2");
    }
    logger.info("SHANGHAIBank:taskKey="+taskkey+"获得的登录状态码是"+stauts);

    //临时修复，后期优化上海登录
    if("登录中,请稍候".equals(stauts)){
        Thread.sleep(2000);
        stauts = "SUCCESS";
    }
    imgResult.statuts = stauts;

    var checkSmsFunc = function (imgResult) {
        return equals(imgResult.statuts, "SUCCESS")
    }
    var getSmsErrormsgFunc = function (imgResult) {
        var taskkey=context.get(LUA_TASK_KEY);
        if (imgResult.statuts.equals("WRONGCODE")) {
            imgResult.errorMsg = "图片验证码错误"
        }else {
            imgResult.errorMsg = imgResult.statuts;
        }
        return imgResult.errorMsg
    }
    return assertTrueOrThrowException(imgResult, checkSmsFunc, getSmsErrormsgFunc)
}

function inputSmsSH() {

    // 判断登录后的页面是否成功
    var loginAfterResult = {}
    var checkSmsStatutsFunc = function (loginAfterResult) {
        var taskkey=context.get(LUA_TASK_KEY);
        logger.info("SHANGHAI taskkey={}，检查当前页面是否为密码过于简单页面",taskkey);
        var simplePasswordCheck = luaFuncs.simplePasswordCheck();
        logger.info("SHANGHAI taskkey={}，检查登录后状态收到的状态码为{}",taskkey,simplePasswordCheck);
        loginAfterResult.statuts = simplePasswordCheck
        return equals(simplePasswordCheck, "OK")
    };
    var getSmsErrormsg = function (loginAfterResult) {
        if (loginAfterResult.statuts.equals("ANEWINFO"))
        {
            loginAfterResult.errorMsg = "网上银行自助开通，需要设置登录的密码及各项信息"

        }else if (loginAfterResult.statuts.equals("SETLOGINPASSWORD"))
        {
            loginAfterResult.errorMsg = "当前账户需要接受合约，并且设置用户昵称和登录密码等内容"

        }else if (loginAfterResult.statuts.equals("OBLIGATEINFO"))
        {
            loginAfterResult.errorMsg = "当前账户需要设置网银预留信息，完善登录信息"

        }else if (loginAfterResult.statuts.equals("ADDTHISACCOUNT"))
        {
            loginAfterResult.errorMsg = "：尊敬的用户，您已注册我行个人网银，您可将此账户添加至个人网银中进行操作"

        }else if (loginAfterResult.statuts.contains("RESETPASSWORD"))
        {
            loginAfterResult.errorMsg = "当前账户需要重新设置网银登录密码，需要用户完善登录信息"

        }else if (loginAfterResult.statuts.contains("SIMPLEPASSWORD"))
        {
            loginAfterResult.errorMsg = "您的密码过于简单，请登录官网重置";
        }else {
            loginAfterResult.errorMsg = "新出现的错误错误";
        }
        return loginAfterResult.errorMsg
    };
    assertTrueOrThrowException(loginAfterResult, checkSmsStatutsFunc, getSmsErrormsg);

    // 短信验证
    var smsCheckFunc = function () {
        Thread.sleep(2000);
        var taskkey=context.get(LUA_TASK_KEY);
        logger.info("ShangHaiBank:taskKey="+taskkey+"检查是否需要验证码");
        var smsCheck = luaFuncs.smsCheck();
        logger.info("ShangHaiBank:taskKey="+taskkey+"获取到的检查是否需要短信的状态码是"+smsCheck);
        if (smsCheck.equals("NEED")) {
            logger.info("ShangHaiBank:taskKey=" + taskkey + "发送短信验证码");
            click_by_id("resend");
            var screenShots = luaFuncs.getScreenShots();
            logger.info("发送短信验证码后的截图路径为{}", screenShots);
            logger.info("SHANGHAIBank:taskKey=" + taskkey + "获取验证码");
            var smsInfo = waitSmsCodeBySeconds(context, 120);
            //提交验证码 并且检查是否正确
            show();
            Thread.sleep(200);
            var status = luaFuncs.submitSmsAndCheck(smsInfo);
            hide();
            return equals(status, "OK")
        }
        return true;

    }
    var getSmsErrorMsg = function () {
        return "短信验证码错误"
    }
    return assertTrueOrThrowException("", smsCheckFunc, getSmsErrorMsg)

}


/**
 * 判断当前页面是否是正确的页面  如果不是，则循环等待
 * @return
 * @throws InterruptedException
 */
function getRightHtml(client,currentHtml,flag)  {
    var contains = currentHtml.contains(flag);
    var index=1;
    var sleepTime=1500;
    while(!contains){
        if (index>3) {
            break;
        }
        Thread.sleep(sleepTime);
        index++;
        sleepTime=sleepTime*index;
        logger.info("SHANGHAIBank:taskKey=" +context.get(LUA_TASK_KEY)+"第"+index+"次获取当前页面，睡眠时间为"+sleepTime);
        currentHtml=get_html();
        contains=currentHtml.contains(flag);
    }
    return currentHtml;
}
function crawlSH() {
    //show();
    var taskkey=context.get(LUA_TASK_KEY);
    // var mainPageStatus = luaFuncs.judgeMainPage();
    // var screen_prints = screen_print();
    // logger.info("截取当前ie截图,截图路径为{}",screen_prints);
    // logger.info("SHBank:taskKey="+taskkey+"获取到的检查是否为主页的状态为"+mainPageStatus);
    // if (!mainPageStatus.equals("OK")) {
    //     logger.info("SHBank taskkey="+taskkey+"页面未正常跳转，停止抓取");
    //     throw new BankException(BankConstants.BALO_99601_50,"登录成功后，判断是否进入主页结果为：未进入主页");
    // }
   // var list=new ArrayList();
    logger.info("SHBank taskKey=" +taskkey + " 开始抓取账户信息");
    logger.info("SHBank taskKey=" + taskkey +"获取账户名字");
    var frameHtml=ajax_get("https://ebanks.bankofshanghai.com/pweb/welcome.do");
    var screen_prints = screen_print();
    logger.info("截取当前ie截图,截图路径为{}",screen_prints);
    storeDataToFile(context,frameHtml, "index.html");
    var accountDoc = Jsoup.parse(frameHtml);
    var name_on_card="";
    try {
        name_on_card=accountDoc.select("p.siz16").get(0).text().trim().replaceAll(",", "").replaceAll("，", "");
        logger.error("name_on_card=============="+name_on_card);
        name_on_card=name_on_card.substring(0, name_on_card.length-2);
    } catch ( e) {
        logger.error("name_on_card=============="+name_on_card);
        statCaughtException(context, e);
        logger.info("SHBank taskKey=" + taskkey +"主页账户卡名字获取解析失败，错误原因为：{}",e.getMessage());
    }
    logger.info("获取账户卡信息列表");
    Thread.sleep(2000);
    var url="https://ebanks.bankofshanghai.com/pweb/ActViewPre.do?_navigator=pquery.pactqry.ActView";
    var cardListHtml = ajax_get(url);
    storeDataToFile(context,cardListHtml, "cardList.html");
    var doc = Jsoup.parse(cardListHtml);
    var elements = doc.select("body > div > form > div.Box1 > div.content_all > table > tbody > tr");
    if (elements.isEmpty()) {
        logger.info("获取账户的账户卡的列表失败，停止抓取");
        throw new 	BankException(BankConstants.BALO_20304_30,"解析账户列表页面失败，停止抓取");
    }
    var cardList=new LinkedList();
    for (var i = 0; i < elements.size(); i++) {
        if (i==0) {
            continue;
        }
        var map=new HashMap();
        var element = elements.get(i);
        var type = element.select("tr>td:nth-child(1)").get(0).text();
        //var fullcardNum=element.select("tr>td:nth-child(3)").get(0).text();
        var fullcardNumSelect = element.select("tr>td:nth-child(3)");
        var fullcardNum="";
        if (fullcardNumSelect.isEmpty()) {
            logger.info("当前卡号为空，停止填充数据");
            continue;
        }
        var cardStatus = element.select("tr > td:nth-child(5)");
        if (!cardStatus.isEmpty()&&cardStatus.html().contains("待添加")) {
            logger.info("当前卡号未添加，停止填充数据");
            continue;
        }
        fullcardNum=fullcardNumSelect.get(0).text();
        var openBank=element.select("td:nth-child(5)").get(0).text();//借记卡开户行
        var creditOpenBank=element.select("td:nth-child(4)").get(0).text();//信用卡开户行
        var creditCardStatus=element.select("td:nth-child(5)").get(0).text();
        map.put("creditCardStatus", creditCardStatus);
        map.put("creditOpenBank", creditOpenBank);
        map.put("cardType", type);
        map.put("fullCardNum", fullcardNum);
        map.put("openBank", openBank);
        map.put("nameOnCard", name_on_card);
        cardList.add(map);
    }
    if (cardList.size()==0) {
        logger.info("获取到卡号信息列表为空，停止抓取");
        throw new 	BankException(BankConstants.BALO_20304_30,"获取到卡号信息列表为空，停止抓取");
    }
    for each(var  map in cardList) {
        var cardType=map.get("cardType");
        logger.info("SHBANK taskKey{}，抓取{}信息",taskkey,cardType);
        if (cardType.contains("借记卡")) {
            logger.info("SHBank taskKey={}，开始抓取借记卡信息", taskkey);
            crawlDepositeCardsInfo(map);
        }
        if (cardType.contains("信用卡")) {
            logger.info("SHBank taskKey={}，开始抓取信用卡信息", taskkey);
            var status=map.get("creditCardStatus");
            if(status.contains("待添加")){
                logger.info("上海 taskKey= {} ，当前账户卡号{}未添加，不抓取",context.get(LUA_TASK_KEY),map.get("fullCardNum"))
                continue;
            }
            crawlCreditCardsInfo(map);
            creditCardNum++;
        }
    }
}



/**
 * 抓取借记卡 信息
 * @param basicInfo
 * @throws Exception
 */
function crawlDepositeCardsInfo(basicInfo) {
    var list=new ArrayList();
    context.put("debit_data", list);
    var taskkey=context.get(LUA_TASK_KEY);
    logger.info("开始抓取该账户借记卡信息");
    var creditCardAllData=new CreditCardAllData();
    list.add(creditCardAllData);
    var depositInfoUrl="https://ebanks.bankofshanghai.com/pweb/SubActsQry1.do";
    var  param=new HashMap();
    //AccountNo=620522003540972724&Alias=&AccountBankAcType=PDBC
    var full_card_num=basicInfo.get("fullCardNum");
    param.put("AccountNo", full_card_num);
    param.put("Alias", "");
    param.put("AccountBankAcType", "PDBC");
    logger.info("请求借记卡的存款信息");
    var depositInfoHtml = ajax_post(depositInfoUrl, param);
    storeDataToFile(context,depositInfoHtml, "depositInfoHtml.txt");
    //填充基本数据
    creditCardAllData.setCardId(UUID.randomUUID().toString());
    creditCardAllData.setBankName("上海银行");
    creditCardAllData.setFullCardNum(full_card_num);
    if (full_card_num.length>4) {
        creditCardAllData.setCardNum(full_card_num.substring(full_card_num.length-4,full_card_num.length));
    }
    creditCardAllData.setCardType("借记卡");
    creditCardAllData.setNameOnCard(basicInfo.get("nameOnCard"));
    creditCardAllData.setOpenBank(basicInfo.get("openBank"));
    creditCardAllData.setCashBalance(null);
    creditCardAllData.setCashLimit(null);
    creditCardAllData.setCreditLimit(null);

    parseDepositInfo(depositInfoHtml, creditCardAllData);
    logger.info("开始抓取借记卡账单信息");
    //https://ebanks.bankofshanghai.com/pweb/ActTrsInfoQry.do
    //抓取12个月的账单
    var queryBillHtml=ajax_get("https://ebanks.bankofshanghai.com/pweb/ActTrsInfoQryPre.do?_navigator=pquery.pactqry.ActTrsQry");
    storeDataToFile(context,queryBillHtml, "quertBillMonth.txt");
    var doc = Jsoup.parse(queryBillHtml);
    var elements = doc.select(".Box1 > form:nth-child(2)>input");
    if (elements.isEmpty()) {
        logger.info("借记卡请求参数获取失败，停止抓取");
        return;
    }
    var billDetailParam=new LinkedHashMap();
    for each(var element in elements) {
        var name = element.attr("name");
        var value=element.attr("value");
        billDetailParam.put(name, value);
    }
    var elements2 = doc.select("#submtable>input");
    for each(var element in elements2) {
        var name = element.attr("name");
        var value=element.attr("value");
        billDetailParam.put(name, value);
    }
    //暂定为人民币
    billDetailParam.put("CurrencyCode", "CNY");
    billDetailParam.put("CurrencyCRFlag", "C");
    billDetailParam.put("CurrencyCodeName", "CNY");
    billDetailParam.put("CurrencyCRFlagName", "C");
    //&MinTrsAmount=0.00&MaxTrsAmount=999%2C999%2C999%2C999.99
    billDetailParam.put("MinTrsAmount", "0.00");
    billDetailParam.put("doItButton", "查询");
    billDetailParam.put("TrsType", "A");
    billDetailParam.put("AccountNo", full_card_num);
    billDetailParam.put("AccountBankAcType", "PDBC");
    billDetailParam.put("SubAcNoAlias", full_card_num+"/PDBC//CNY/C");
    billDetailParam.put("MaxTrsAmount", "999,999,999,999.99");
    var option=doc.select(".fontBig > select:nth-child(1) > option:nth-child(1)").attr("value");
    var selectName=doc.select(".fontBig > select:nth-child(1)").attr("name");
    billDetailParam.put(selectName, option);
    //&CurrencyCode=CNY&CurrencyCRFlag=C&CurrencyCodeName=CNY&CurrencyCRFlagName=C
    var calendar=Calendar.getInstance();
    var currentMonth=calendar.get(Calendar.MONTH)+1;
    for(var i=0;i<12;i++){
        var month = calendar.get(Calendar.MONTH)+1;
        var dayStr="";
        var monthStr="";
        if (month!=currentMonth) {
            //dayStr="30";
            dayStr=""+calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        }else{
            var day=calendar.get(Calendar.DAY_OF_MONTH);
            dayStr=Integer.toString(day);
        }
        if (month<10) {
            monthStr="0"+month;
        }else{
            monthStr=Integer.toString(month);
        }
        var year=calendar.get(Calendar.YEAR);
        var startDate=year+"-"+monthStr+"-01";
        var endDate=year+"-"+monthStr+"-"+dayStr;
        billDetailParam.put("BeginDate", startDate);
        billDetailParam.put("EndDate", endDate);
        logger.info("抓取{}月账单",startDate);
        crawlDepositBill(creditCardAllData, billDetailParam);
        calendar.add(Calendar.MONTH, -1);
    }
}

/**
 * 抓取借记卡账户的账单信息
 * @param creditCardAllData
 * @param map
 * @throws Exception
 */
function crawlDepositBill( creditCardAllData,map) {
    var  param=new LinkedHashMap();
    var entrySet = map.entrySet();
    for each(var entry in entrySet) {
        var key = entry.getKey();
        var value = entry.getValue();
        param.put(key, value);
    }
    var url="https://ebanks.bankofshanghai.com/pweb/ActTrsInfoQry.do";
    logger.info("请求{}月账单",param.get("BeginDate"));
    var billHtml = ajax_post(url, param);
    storeDataToFile(context,billHtml, "1_bills_"+depositBillNum+".txt");
    depositBillNum++;
    var startDate=param.get("BeginDate");
    var doc = Jsoup.parse(billHtml);
    var info = doc.select("#EEE").html();
    var billAllData=new BillAllData();
    billAllData.setBillId(UUID.randomUUID().toString());
    billAllData.setBankName("上海银行");
    try {
        billAllData.setBillDate(yyyy_MM_dd_PARSER.parse(startDate));
    } catch (e) {
        logger.info("账单日期转化异常",e);
        billAllData.setBillDate(null);
    }
    billAllData.setBillMonth(startDate.substring(0, 7));
    billAllData.setBillType("");
    billAllData.setNewBalance(null);
    billAllData.setUsdNewBalance(null);
    billAllData.setMinPayment(null);
    billAllData.setUsdMinPayment(null);
    billAllData.setMinPayment(null);
    billAllData.setLastBalance(null);
    billAllData.setUsdLastBalance(null);
    billAllData.setLastPayment(null);
    billAllData.setUsdLastPayment(null);
    billAllData.setNewCharges(null);
    billAllData.setUsdNewCharges(null);
    billAllData.setInterest(null);
    billAllData.setUsdInterest(null);
    billAllData.setCreditLimit(null);
    billAllData.setCashLimit(null);
    billAllData.setUsdCashLimit(null);
    billAllData.setUsdCreditLimit(null);
    creditCardAllData.getBills().add(billAllData);
    if (info.contains("没有查询到符合条件的交易记录")) {
        logger.info("当前月：{}没有账单信息，停止抓取",startDate);
        return;
    }
    var downLoadUrl="https://ebanks.bankofshanghai.com/pweb/ActTrsInfoQry.do?_Download=xls&_MultiReports=false&_HidePdfToolBar=false&_ForbidPdfPrint=false";
    param.put("currentIndex", "0");
    param.put("recordNumber","1");
    param.put("GotoField","");
    param.put("ListSize","1");
    var billPath = luaFuncs.ajaxPostFile(downLoadUrl, param);
    if (billPath.equals("EMPTYPATH") || billPath == null || billPath.length == 0) {
        logger.info("请求借记卡" +  startDate+ "月数据，请求获取数据失败,停止解析该月");
        return;
    }

    //luaFuncs.copyFile(billPath,context.get(LUA_TASK_KEY),  "1_" + startDate + ".xls");

    try {
        storeDataToFile(context, billPath, "1_" + startDate + ".xls");
        var readExcel =read2003Excel(new File(billPath));
        logger.info("解析{}月的excel数据，填充数据",startDate);
        parseDepositBillExcel(billAllData, readExcel);

    } catch ( e) {
        statCaughtException(context, e);
        logger.info("解析借记卡账单的excel失败，停止解析",e);
    }
}
/**
 * 解析借记卡的账单excel
 * @param billAllData
 * @param billLists
 */
function parseDepositBillExcel( billAllData,billLists){
    if (billLists!=null && billLists.size()>0) {
        var fullcardNum="";
        var currecy="";
        if (billLists.size()>0) {
            var allInfoList = billLists.get(1);
            if (allInfoList.size()>10) {
                fullcardNum= allInfoList.get(2);
                var spentMoney= allInfoList.get(7);//支出
                currecy= allInfoList.get(10);//币种
            }
        }
        var shopping_sheets = billAllData.getShoppingSheets();
        var order_index=shopping_sheets.size()+1;
        for (var i = 0; i < billLists.size(); i++) {
            if (i<=3) {
                continue;
            }
            var list = billLists.get(i);
            var transDate =  list.get(0);
            var descrption= list.get(2);
            var amountMoney= list.get(3);//收入
            var spendMoney= list.get(4);//支出
            var balance= list.get(5);//账户余额
            var name_on_opposite_card= list.get(7);
            var oppsoite_cardNum= list.get(8);
            var opposite_bank= list.get(10);
            var method= list.get(11);
            var remark= list.get(12);
            var expense=new Expense();
            var currency_type=CreditResultUtil.convertCurr(currecy);
            if(StringUtils.isBlank(currency_type)||currency_type.trim().length==0||currency_type.contains("其他")){
                currency_type="CNY";
            }

            expense.setCurrencyType(currency_type);
            expense.setBalance(CreditResultUtil.StringToBigDecimal(balance));
            expense.setId(UUID.randomUUID().toString());
            if (fullcardNum.length>4) {
                expense.setCardNum(fullcardNum.substring(fullcardNum.length-4, fullcardNum.length));
            }
            expense.setDescription(descrption);
            expense.setNameOnOppositeCard(name_on_opposite_card);
            expense.setOppositeBank(opposite_bank);
            expense.setOppositeCardNo(oppsoite_cardNum);
            expense.setNameOnOppositeCard(name_on_opposite_card);
            expense.setOrderIndex(order_index);
            order_index++;
            expense.setRemark(remark);
            logger.info("transDate="+transDate);
            try {
                expense.setTransDate(yyyy_MM_dd_HH_mm_ss_PARSER.parse(transDate + ":00"));
            } catch (e) {
                logger.info("解析账单时间异常");
            }
            try {
                expense.setTransMethod(method);
                expense.setPostDate(yyyy_MM_dd_PARSER.parse(transDate.substring(0, 10)));
                if (amountMoney != null && amountMoney.trim().length > 0) {//收入有值 为负数
                    expense.setCategory(CategoryUtil.getDebitCategory(descrption, amountMoney));
                    amountMoney = amountMoney.replaceAll("\\+", "");
                    logger.info("amountMoney="+amountMoney);
                    expense.setAmountMoney(CreditResultUtil.StringToBigDecimal(amountMoney).divide(new BigDecimal("-1")));
                }
                // if (spendMoney != null && spendMoney.trim().length > 0) {//支出有值 为正
                //     expense.setCategory(CategoryUtil.getDebitCategory(descrption, spendMoney));
                //     spendMoney = spendMoney.replaceAll("\\-", "");
                //     logger.info("spendMoney="+spendMoney);
                //     expense.setAmountMoney(CreditResultUtil.StringToBigDecimal(spendMoney));
                // }
                expense.setCategory(CategoryUtil.getDebitCategory(descrption, amountMoney));
            } catch (e) {
                shopping_sheets.add(expense);
                statCaughtException(context,e);
                logger.info("上海借记卡账单解析异常，停止解析，继续抓取",e);
            }
            shopping_sheets.add(expense);

        }
    }
}
/**
 * 根据描述来判断消费类型
 * @param descrption
 * @return
 */
function checkDepositeBillCategory(descrption,amountMoney){
    var category="";
    if (amountMoney.contains("+")) {//收入
        if (descrption.contains("工资")) {
            category="SALARY";
        }else if(descrption.contains("奖金")) {
            category="BONUS";
        }else if (descrption.contains("利息")) {
            category="ACCRUAL";
        }else if (descrption.contains("存现")) {
            category="DEPOSIT";
        }else if (descrption.contains("转账")) {
            category="TRANSFER";
        }else if (descrption.contains("借贷")) {
            category="LOANS";
        }else if (descrption.contains("冲账")) {
            category="REVERSE";
        }else if (descrption.contains("收益")) {
            category="EARNINGS";
        }else if (descrption.contains("报销")) {
            category="CLAIM";
        }else {
            category="OTHERREVENUE";
        }
    }
    if (amountMoney.contains("-")) {//支出
        if (descrption.contains("取现")) {
            category="WITHDRAW";
        }else if(descrption.contains("手续费")) {
            category="HANDLINGFEE";
        }else if (descrption.contains("理财")) {
            category="FINANCE";
        }else if (descrption.contains("消费")) {
            category="CONSUMPTION";
        }else if (descrption.contains("社保")) {
            category="SOCIALSECURITY";
        }else if (descrption.contains("通讯费")) {
            category="COMMUNICATIONFEE";
        }else if (descrption.contains("生活费")) {
            category="LIVINGEXPENSE";
        }else if (descrption.contains("转账")) {
            category="TRANSFER";
        }else if (descrption.contains("还贷")) {
            category="REPAYMENT";
        }else if (descrption.contains("房租")) {
            category="RENT";
        }else if (descrption.contains("其他费用")) {
            category="OTHERFEE";
        }else {
            category="OTHEREXPENSE";
        }
    }
    return category;
}

/**
 * 解析借记卡的存款等信息
 * @param depositInfoHtml
 * @param creditCardAllData
 */
function parseDepositInfo(depositInfoHtml, creditCardAllData){
    logger.info("开始解析借记卡的存款等信息");
    try {
        var doc = Jsoup.parse(depositInfoHtml);
        var balanceDescription = doc.select("span.fontPage:nth-child(1) > strong:nth-child(1)").get(0).text();
        var balanceAndDescrption = balanceDescription.split("：");
        var balance="";
        if (balanceAndDescrption.length>1) {
            balance=balanceAndDescrption[1];
            creditCardAllData.setBalance(CreditResultUtil.StringToBigDecimal(balance));
        }
        var elements = doc.select("#SavListTable > tbody:nth-child(1)>tr");
        if (elements.isEmpty()) {
            logger.info("获取借记卡的存款等信息失败，停止解析");
            return;
        }
        var deposits = creditCardAllData.getDeposits();
        for(var i=0;i<elements.size();i++){
            if (i==0) {
                continue;
            }
            var element = elements.get(i);
            var depositeType = element.select("tr>td:nth-child(1)").get(0).text();//活期
            logger.info("获取到的借记卡存储种类为{}",depositeType);
            var deposit=new CreditCardTimeDeposit();
            var currecy = element.select("tr>td:nth-child(2)").get(0).text();//人民币
            var openTime = element.select("tr>td:nth-child(5)").get(0).text();//开户时间
            logger.info("openTime="+openTime);
            var endDate = element.select("tr>td:nth-child(6)").get(0).text().replace("---","");//到期日期
            var insert = element.select("tr>td:nth-child(7)").get(0).text().replace("---","");// % 利率
            //td.tdValue2:nth-child(8) > div:nth-child(1)
            var remainBalance=element.select("tr>td:nth-child(8)>div").get(0).text();//账户余额
            var avaliableBalance=element.select("tr>td:nth-child(9)>div").get(0).text();//可用额度
            deposit.setBalance(CreditResultUtil.StringToBigDecimal(remainBalance));
            if (insert.trim().replaceAll("-", "").length>0) {
                deposit.setInterest(CreditResultUtil.StringToBigDecimal(insert).divide(new BigDecimal("100")));
            }

            var currency_type=CreditResultUtil.convertCurr(currecy);
            if(StringUtils.isBlank(currency_type)||currency_type.trim().length==0||currency_type.contains("其他")){
                currency_type="CNY";
            }

            deposit.setCurrencyType(currency_type);
            if (depositeType.contains("活期")) {
                deposit.setDepositDate(StringUtils.isBlank(openTime)?null:yyyy_MM_dd_PARSER.parse(openTime));
                deposit.setDepositType(depositeType);
                deposit.setPeriodUnit("");
                deposit.setInterest(null);
                deposit.setPeriod(null);
            }
            if (depositeType.contains("整")) {
                deposit.setDepositDate(StringUtils.isBlank(openTime)?null:yyyy_MM_dd_PARSER.parse(openTime));
                deposit.setDepositType(depositeType);
                deposit.setDueDate(StringUtils.isBlank(endDate)?null:yyyy_MM_dd_PARSER.parse(endDate));
                deposit.setPeriod(Integer.parseInt("0"));
                deposit.setPeriodUnit("");
            }
            //银行开卡时间
            creditCardAllData.setOpenTime(StringUtils.isBlank(openTime)?null:yyyy_MM_dd_PARSER.parse(openTime));
            deposits.add(deposit);
        }
    } catch (e) {
        statCaughtException(context,e);
        logger.info("借记卡存款等信息解析出错，停止解析，继续抓取",e);
    }

}


/**
 * 抓取信用卡信息
 * @param basicInfo
 * @throws InterruptedException
 */
function crawlCreditCardsInfo(basicInfo) {
    var list=new ArrayList();
    context.put("credit_data", list);
    var creditCardAllData=new CreditCardAllData();
    list.add(creditCardAllData);
    //抓取账户的基本信息
    crawlBasicInfo(creditCardAllData,basicInfo);
    //抓取未结账单
    crawlDoneBills(creditCardAllData );
    crawlUndoneBill(creditCardAllData);

}






/**
 * 抓取已结账单信息
 * @param creditCardAllData
 * @param client
 * @throws InterruptedException
 */
function crawlDoneBills(creditCardAllData){
    logger.info("BOSHBank taskKey=" +context.get(LUA_TASK_KEY)+"获取查询已结账单信息页面");
    var queryBillUrl="https://ebanks.bankofshanghai.com/pweb/CreditBillOutQueryPre.do?_navigator=pcreditcard.creditpaymgmt.BillOutQry";
    var queryBillHtml = ajax_get(queryBillUrl);
    storeDataToFile(context,queryBillHtml, creditCardNum+"_queryMonthHtml.txt");
    var doc = Jsoup.parse(queryBillHtml);

    var queryMonths = RegexUtils.GetText(queryBillHtml, "var dueDates= *(.*)").replaceAll(";", "");//['','','2017-08-06']
    var queryDate=RegexUtils.GetText(queryBillHtml, "var dataX=*(.*)").replaceAll(";", "");//['2016-10', '2016-11', '2016-12', ]
    var monthArray =null;
    var dateArray=null;
    try {
        monthArray=JSON.parse(queryMonths);
        dateArray=JSON.parseArray(queryDate);
    } catch (e) {
        statCaughtException(context, e);
        logger.info("解析账单月份失败");
    }
    if (monthArray==null  || monthArray.size()==0) {
        logger.info("解析账单月份失败，停止抓取");
        return;
    }
    var monthLists=new ArrayList();
    for(var i=0;i<monthArray.size();i++){
        var month = monthArray.getString(i);
        if (month.trim().length>0) {
            var  map=new HashMap();
            map.put("index", ""+i);
            map.put("month", month);
            monthLists.add(map);
        }
    }
    logger.info("当前账户信用卡可以查询的月份一共有{}个月",monthLists.size());
    if (monthLists.size()==0) {
        logger.info("当前账户的信用卡无可以查询的账单月，停止抓取");
        return;
    }
    for each (var  map in monthLists) {
        Thread.sleep(2000);
        var index = map.get("index");
        var date = dateArray.getString(Integer.parseInt(index));
        var month=map.get("month");
        logger.info("抓取{}月的账单",date);
        var param=new HashMap();
        var billMonth=date;
        param.put("BillMonth", date.replaceAll("-", ""));
        param.put("dueDate", month.replaceAll("-", ""));
        //BillMonth=201708&dueDate=20170906
        //https://ebanks.bankofshanghai.com/pweb/CreditBillOutQuery.do
        var billMonthHtml = ajax_post("https://ebanks.bankofshanghai.com/pweb/CreditBillOutQuery.do", param);
        storeDataToFile(context,billMonthHtml, creditCardNum+"_"+date+"_bill.html");
        //var billDoc = Jsoup.parse(billMonth);
        parseDoneBill(billMonthHtml, creditCardAllData, billMonth);

    }




}

/**
 * 解析已出账单的美元信息
 * @param month
 * @param billAllData
 * @param document
 */
function parseUsdDoneBill(document, billAllData,month){
    logger.info("开始解析美元账单信息");
    try {
        var usdFlag = document.select("div.wapper:nth-child(8) > span:nth-child(1)").get(0).text();
        if (usdFlag.contains("美元账户没有交易记录")) {
            logger.info("当前月{}没有美元相关信息,停止解析美元相关",month);
            return;
        }
    } catch ( e) {
        statCaughtException(context, e);
        logger.info("解析美元账单信息失败，停止解析");
        return;
    }
    var usdElement = document.select("div.wapper:nth-child(7) > table:nth-child(1) > tbody:nth-child(1) > tr");
    if (!usdElement.isEmpty()) {
        var shopping_sheets = billAllData.getShoppingSheets();
        var order_index=shopping_sheets.size()+1;
        for(var i=0;i<usdElement.size();i++){
            if (i==0) {
                continue;
            }
            var element = usdElement.get(i);
            var transDate = element.select("td:nth-child(1)").get(0).text();
            var postDate=element.select("td:nth-child(2)").get(0).text();
            var description=element.select("td:nth-child(3)").get(0).text();
            var amount_money=element.select("td:nth-child(4)").get(0).text();
            var cardNum=element.select("td:nth-child(5)").get(0).text();
            var expense=new Expense();
            expense.setId(UUID.randomUUID().toString());
            expense.setCardNum(cardNum);
            expense.setCurrencyType("USD");
            expense.setDescription(description);
            expense.setOrderIndex(order_index);
            order_index++;
            expense.setTransDate(yyyy_MM_dd_HH_mm_ss_PARSER.parse(transDate+" 00:00:00"));
            expense.setPostDate(yyyy_MM_dd_PARSER.parse(postDate));

            expense.setCategory(CreditResultUtil.judgeBillCategory(description));
            if (description.contains("还款")) {
                var money=amount_money.replaceAll("\\-", "").replaceAll("\\+", "");
                var usd_last_payment = billAllData.getUsdLastPayment();
                if (usd_last_payment==null) {
                    usd_last_payment=new BigDecimal("0");
                    usd_last_payment=usd_last_payment.add(CreditResultUtil.StringToBigDecimal("-"+money));
                }else{
                    usd_last_payment=usd_last_payment.add(CreditResultUtil.StringToBigDecimal("-"+money));
                }
                billAllData.setLastPayment(usd_last_payment);
            }
            if (amount_money.contains("+")) {//支出
                expense.setAmountMoney(CreditResultUtil.StringToBigDecimal(amount_money.replaceAll("\\+", "")));
                var usd_new_charges = billAllData.getUsdNewCharges();
                if (usd_new_charges==null) {
                    usd_new_charges=new BigDecimal("0");
                    usd_new_charges=usd_new_charges.add(expense.getAmountMoney());
                }else{
                    usd_new_charges=usd_new_charges.add(expense.getAmountMoney());
                }
                billAllData.setUsdNewCharges(usd_new_charges);
            }
            shopping_sheets.add(expense);
        };
    }
}

/**
 * 解析已出账单
 * @param doneBillHtml
 * @param creditCardAllData
 */
function parseDoneBill(doneBillHtml, creditCardAllData,month){
    logger.info("解析{}月账单",month);
    var doc = Jsoup.parse(doneBillHtml);
    try {
        var billMonth= doc.select(".xyk_tb > tbody:nth-child(1) > tr:nth-child(3) > td:nth-child(2)").get(0).text();
        var last_balance=doc.select(".xyk_tb > tbody:nth-child(1) > tr:nth-child(3) > td:nth-child(3) > span:nth-child(1)").get(0).text().replaceAll("\\+", "").replaceAll("\\-", "");
        //var new_balance=doc.select(".xyk_tb > tbody:nth-child(1) > tr:nth-child(3) > td:nth-child(4)").get(0).text().replaceAll("\\+", "").replaceAll("\\-", "");
        var new_charges=doc.select(".xyk_tb > tbody:nth-child(1) > tr:nth-child(3) > td:nth-child(4)").get(0).text().replaceAll("\\+", "").replaceAll("\\-", "");
        var new_balance=doc.select(".xyk_tb > tbody:nth-child(1) > tr:nth-child(3) > td:nth-child(7)").get(0).text().replaceAll("\\+", "").replaceAll("\\-", "");
        var min_payment=doc.select(".xyk_tb > tbody:nth-child(1) > tr:nth-child(3) > td:nth-child(8)").get(0).text().replaceAll("\\+", "").replaceAll("\\-", "");
        var last_payment=doc.select(".xyk_tb > tbody:nth-child(1) > tr:nth-child(3) > td:nth-child(5)").get(0).text();//上期还款金额，如果没有取当前的还款金额
        var monthInfoAndCreditLimit=doc.select("div.szmx:nth-child(1)").html();
        var monthInfoCreditLimits = monthInfoAndCreditLimit.split("信用卡额度：RMB");
        var creditLimit="";
        if (monthInfoCreditLimits.length>0) {
            creditLimit=monthInfoCreditLimits[1].trim().replaceAll(",", "").replaceAll(",", "").replaceAll("&nbsp; ", "");;
        }
        var begin=monthInfoAndCreditLimit.indexOf("到期还款日：");
        var endIndex=monthInfoAndCreditLimit.indexOf("信用卡额度：RMB");
        var billdate = monthInfoAndCreditLimit.substring(begin, endIndex).trim().replaceAll("&nbsp;", "").replaceAll("到期还款日：", "").replaceAll("\\s", "");;
        var billAllData=new BillAllData();
        billAllData.setBillId(UUID.randomUUID().toString());
        billAllData.setBankName("上海银行");
        //billAllData.setBillDate(yyyy_MM_dd_PARSER.parse(billdate));
        var billDateDay = billDate.substring(billDate.length-2,billDate.length);
        billAllData.setBillDate(yyyy_MM_dd_PARSER.parse(month+"-"+billDateDay));
        billAllData.setPaymentDueDate(yyyy_MM_dd_PARSER.parse(billdate));
        billAllData.setBillMonth(month);
        billAllData.setBillType("DONE");
        billAllData.setLastPayment(CreditResultUtil.StringToBigDecimal("-"+last_payment));
        billAllData.setLastBalance(CreditResultUtil.StringToBigDecimal(last_balance));
        billAllData.setNewBalance(CreditResultUtil.StringToBigDecimal(new_balance));
        billAllData.setMinPayment(CreditResultUtil.StringToBigDecimal(min_payment));
        billAllData.setCreditLimit(CreditResultUtil.StringToBigDecimal(creditLimit));
        billAllData.setNewCharges(CreditResultUtil.StringToBigDecimal(new_charges));
        //在这里取除美元相关信息
        var usd_balance = usdCreditLimitInfoMap.get(basicInfoUsdBalance);
        var usd_credit_limit=usdCreditLimitInfoMap.get(basicInfoUsdCreditLimit);
        var usd_cash_limit=usdCreditLimitInfoMap.get(basicInfoUsdCashLimit);
        billAllData.setUsdCashLimit(null);
        billAllData.setUsdCreditLimit(CreditResultUtil.StringToBigDecimal(usd_credit_limit));
        //如果当前页面也有美元相关信息那么就继续向其中添加

        billAllData.setCashLimit(null);
        //billAllData.setUsdCashLimit(null);
        billAllData.setInterest(null);
        billAllData.setUsdInterest(null);
        //billAllData.setUsdCreditLimit(null);
        billAllData.setUsdLastBalance(null);
        billAllData.setUsdLastPayment(null);
        billAllData.setUsdMinPayment(null);
        billAllData.setUsdNewBalance(null);
        billAllData.setUsdNewCharges(null);


        var usdElement = doc.select(".xyk_tb > tbody:nth-child(1) > tr:nth-child(5) > td:nth-child(1)");
        if (!usdElement.isEmpty()&&usdElement.toString().contains("美元")) {
            logger.info("当前账户的账单具有美元的相关信息");
            var usd_last_balance = doc.select(".xyk_tb > tbody:nth-child(1) > tr:nth-child(5) > td:nth-child(2) > span:nth-child(1)").get(0).text().replaceAll("\\+", "").replaceAll("\\-", "");
            var usd_new_charges=doc.select(".xyk_tb > tbody:nth-child(1) > tr:nth-child(5) > td:nth-child(3)").get(0).text().replaceAll("\\+", "").replaceAll("\\-", "");
            var usd_last_payment=doc.select(".xyk_tb > tbody:nth-child(1) > tr:nth-child(5) > td:nth-child(4)").get(0).text().replaceAll("\\+", "").replaceAll("\\-", "");
            var usd_new_balance=doc.select(".xyk_tb > tbody:nth-child(1) > tr:nth-child(5) > td:nth-child(6) > span:nth-child(1)").get(0).text().replaceAll("\\+", "").replaceAll("\\-", "");
            var usd_min_payment=doc.select(".xyk_tb > tbody:nth-child(1) > tr:nth-child(5) > td:nth-child(7)").get(0).text().replaceAll("\\+", "").replaceAll("\\-", "");
            billAllData.setUsdLastBalance(CreditResultUtil.StringToBigDecimal(usd_last_balance));
            billAllData.setUsdNewCharges(CreditResultUtil.StringToBigDecimal(usd_new_charges));
            billAllData.setUsdLastPayment(CreditResultUtil.StringToBigDecimal("-"+usd_last_payment));
            billAllData.setUsdNewBalance(CreditResultUtil.StringToBigDecimal(usd_new_balance));
            billAllData.setUsdMinPayment(CreditResultUtil.StringToBigDecimal(usd_min_payment));
        }


        creditCardAllData.getBills().add(billAllData);

        var order_index=1;
        try {
            logger.info("解析{}月账单详情",month);
            var installmentList=new LinkedList();//分期本金的集合
            var handFeeList=new LinkedList();//分期手续费的集合
            var elements = doc.select("div.wapper:nth-child(3) > table:nth-child(1) > tbody:nth-child(1)>tr");
            var installmentFlag="";
            for(var i=0;i<elements.size();i++){
                if (i==0) {
                    continue;
                }
                var element = elements.get(i);
                var transDate = element.select("td:nth-child(1)").get(0).text();
                var postDate=element.select("td:nth-child(2)").get(0).text();
                var description=element.select("td:nth-child(3)").get(0).text();
                var amount_money=element.select("td:nth-child(4)").get(0).text();
                var cardNum=element.select("td:nth-child(5)").get(0).text();

                if (description.contains("分期")&& description.contains("手续费") || description.contains("本金") ) {
                    //1.确定全部为分期的内容(不含本金转回或者差额等)，将其存放到本金一个集合  手续费一个集合
                    //2.使用排序将其按照金额大小将手续费排序
                    //3.分别对应手续费和本金放到一个对象中，放入BillAllDate对象中
                    if (description.contains("手续费")) {
                        var installment=new Installment();
                        installment.setTransferfeeDesc("");
                        var handFee=amount_money.substring(0, amount_money.length-1);
                        installment.setHandingFee(CreditResultUtil.StringToBigDecimal(handFee));
                        installment.setHandingfeeDesc(description);
                        handFeeList.add(installment);
                    }
                    if (description.contains("本金")&& !description.contains("转回")) {
                        var installment=new Installment();
                        installment.setTransferfeeDesc("");
                        installment.setShoppingsheetId(UUID.randomUUID().toString());
                        installment.setBillId(null);
                        installment.setTransferFee(null);
                        installment.setCurrencyType("CNY");
                        installment.setInstallmentDesc(description);
                        installment.setTransDate(yyyy_MM_dd_HH_mm_ss_PARSER.parse(transDate+" 00:00:00"));
                        installment.setPostDate(yyyy_MM_dd_PARSER.parse(postDate));
                        var installmentCount = getInstallmentCount(description);
                        installment.setCurrentMonth(installmentCount[0]);
                        installment.setTotalMonth(installmentCount[1]);
                        installment.setInstallmentType(judgeInstallmentType(description));
                        var installmentMoney=amount_money.substring(0, amount_money.length-1);
                        installment.setAmountMoney(CreditResultUtil.StringToBigDecimal(installmentMoney));
                        installmentList.add(installment);
                    }
                }
                var expense=new Expense();
                expense.setNameOnOppositeCard("");
                expense.setOppositeBank("");
                expense.setOppositeCardNo("");
                expense.setRemark("");
                expense.setTransAddr("");
                expense.setTransChannel("");
                expense.setTransMethod("");


                expense.setId(UUID.randomUUID().toString());
                expense.setCardNum(cardNum);
                expense.setBalance(null);//交易明细的balance
                expense.setCurrencyType("CNY");
                expense.setDescription(description);
                expense.setOrderIndex(order_index);
                order_index++;
                expense.setTransDate(yyyy_MM_dd_HH_mm_ss_PARSER.parse(transDate+" 00:00:00"));
                expense.setPostDate(yyyy_MM_dd_PARSER.parse(postDate));
                //var category=CreditResultUtil.judgeBillCategory(description);
                var category=CategoryUtil.getCreditCategory("SHANGHAI", description, amount_money);
                if (category.equals("OTHERFEE")&&description.contains("公司")&&amount_money.contains("+")) {
                    category="SHOPPING";//即 当无法匹配时，判断描述包含公司、同时金额为支出的时候 设置字段为SHOPPING
                }
                if (category.equals("INSTALLMENT") && (description.contains("差额")||description.contains("本金转回"))) {
                    category="OTHERFEE";//当匹配为分期的时候，同时含有差额 或者本金转回等的时候，将其归类为
                }
                expense.setCategory(category);
                if (amount_money.contains("+")) {//支出
                    expense.setAmountMoney(CreditResultUtil.StringToBigDecimal(amount_money.replaceAll("\\+", "")));
                    //	BigDecimal new_charges = billAllData.getNewCharges().add(expense.getAmountMoney());
                    //billAllData.setNewCharges(new_charges);
                }
                else if (amount_money.contains("-")){
                    expense.setAmountMoney(CreditResultUtil.StringToBigDecimal(amount_money.replaceAll("\\-", "")).divide(new BigDecimal(-1)));
                    //billAllData.setNewCharges(billAllData.getNewCharges().add(expense.getAmountMoney()));
                    //billAllData.setLastPayment(billAllData.getLastPayment().add(expense.getAmountMoney()));//
                }

                billAllData.getShoppingSheets().add(expense);

            }
            //在这将分期本金和手续费分别对应起来
            if (installmentList.size()!=0) {
                parseInstallmentAndHandFee(billAllData, installmentList, handFeeList);
            }

        } catch (e) {
            statCaughtException(context, e);
            logger.info("解析{}月账单时，解析账单详情页面出错",month);
            print(e.message)

        }
        //解析美元相关信息
        parseUsdDoneBill(doc,billAllData,month);

    } catch (e) {
        statCaughtException(context, e);
        logger.info("解析{}月账单页面出错",month);
        print(e.message)
    }
}

/**
 *  将分期本金和手续费分别对应起来
 * @param billAllData
 * @param installmentList 分期本金集合
 * @param handFeeList 分期手续费集合
 */
function parseInstallmentAndHandFee( billAllData,installmentList, handFeeList){
    logger.info("分别对应{}月账单的分期分期手续费",billAllData.getBillMonth());
    bubbleSort(installmentList,"");
    bubbleSort(handFeeList, "handfee");
    if (handFeeList.size()==installmentList.size()) {
        for (var i = 0; i < installmentList.size(); i++) {
            var installment = installmentList.get(i);
            var handFee = handFeeList.get(i);
            installment.setHandingFee(handFee.getHandingFee());//
            installment.setHandingfeeDesc(handFee.getHandingfeeDesc());
        }
    }else{
        logger.info("ABCBank taskkey={}分期手续费与分期对应出错,即分期和本金并不对应，分期的数量为{}，手续费的数量为{}",context.get(LUA_TASK_KEY),installmentList.size(),handFeeList.size());
        for(var i=0;i<installmentList.size();i++){//当现在的本金和 手续费都是按照费用从大到小的顺序排序
            var installment = installmentList.get(i);
            if ((i+1)<=handFeeList.size()) {
                var handFee = handFeeList.get(i);
                installment.setHandingFee(handFee.getHandingFee());
                installment.setHandingfeeDesc(handFee.getHandingfeeDesc());

            }else{
                installment.setHandingFee(null);//如果当前分期对应的手续没有，那么手续费设置为null
                installment.setHandingfeeDesc("");
            }

        }
    }
    billAllData.setInstallments(installmentList);
}



/**
 * 根据分期的金额来排序 从小到大来排序
 * @param list
 */
function bubbleSort( list,flag){
    for(var i=0;i<list.size()-1;i++){
        for(var j=0;j<list.size()-1;j++){
            var currentBigdecimal=null;
            var nextBigdecimal=null;
            if (flag.equals("")) {//为空的时候取本金
                currentBigdecimal=list.get(j).getAmountMoney();
                nextBigdecimal=list.get(j+1).getAmountMoney();
            }else{//不为空的时候取手续费
                currentBigdecimal=list.get(j).getHandingFee();
                nextBigdecimal=list.get(j+1).getHandingFee();//
            }
            if (nextBigdecimal.compareTo(currentBigdecimal)==1) {//当前分期的金额大于下一个
                //int temp=list.get(j);
                var tempInstallment=list.get(j);
                list.set(j, list.get(j+1));
                list.set(j+1, tempInstallment);
            }
        }
    }
}



/**
 * 根据描述获取当前期数  总期数
 * @param descrption
 * @return
 */
function getInstallmentCount(descrption){
    var counts=new Array(2);
    try {
        if (descrption.contains("第")) {
            var currentCount = descrption.substring(descrption.indexOf('第')+1, descrption.indexOf('第')+3);
            if (currentCount.contains("期")) {
                currentCount=currentCount.replaceAll("期", "");
            }
            var current = Integer.parseInt(currentCount);
            counts[0]=current;
        }
        if (descrption.contains("共")) {
            var totalCount = descrption.substring(descrption.indexOf('共')+1, descrption.indexOf('共')+3);
            if (totalCount.contains("期")) {
                totalCount=totalCount.replaceAll("期", "");
            }
            var total = Integer.parseInt(totalCount);
            counts[1]=total;
        }
    } catch ( e) {
        statCaughtException(context, e);
        logger.info("根据描述解析分期期数失败，当前描为{}",descrption);
    }
    return counts;
}


/**
 * 根据分期的描述来判断是否属于哪种分期类型
 * @param installmentDescrption
 * @return
 */
function judgeInstallmentType(installmentDescrption){
    var installmentType="CONSUME";
    if (installmentDescrption!=null && installmentDescrption.length>0) {
        if (installmentDescrption.contains("交易分期")) {
            installmentType="CONSUME";
        }else if (installmentDescrption.contains("现金")) {
            installmentType="CASH";
        }else if (installmentDescrption.contains("账单")) {
            installmentType="BILL";
        }
    }
    return installmentType;
}


/**
 * 抓取基本的信息
 * @param creditCardAllData
 * @param client
 * @throws InterruptedException
 */
function crawlBasicInfo( creditCardAllData,basicInfo) {
//		Map<String, String>map=new LinkedHashMap();
//		logger.info("BOSHBank taskKey=" + this.parameter.getTaskKey() +"获取账户名字");
//		var frameHtml=client.ajax_get("https://ebanks.bankofshanghai.com/pweb/MyActInfoList.do");
//		htmlStorageUtil.store(frameHtml, "index.txt");
//		Document accountDoc = Jsoup.parse(frameHtml);
//		var name_on_card="";
//		try {
//			name_on_card=accountDoc.select("p.siz16").get(0).text().trim().replaceAll(",", "").replaceAll("，", "");
//			name_on_card=name_on_card.substring(0, name_on_card.length()-2);
//		} catch (Exception e) {
//			// TODO: handle exception
//			logger.info("BOSHBank taskKey=" + this.parameter.getTaskKey() +"主页账户卡名字获取解析失败");
//		}
//		logger.info("获取账户卡号Id");
//		var cardInfoHtml=client.ajax_post("https://ebanks.bankofshanghai.com/pweb/MyActInfoList.do",map);
//		htmlStorageUtil.store(cardInfoHtml, "cardInfoHtml.txt");
//		Document cardIdInfoDoc = Jsoup.parse(cardInfoHtml);
//		var cardId=cardIdInfoDoc.select("span.opd2:nth-child(2)").get(0).text().trim();
    var full_card_num=basicInfo.get("fullCardNum");
    creditCardAllData.setFullCardNum(full_card_num);
    creditCardAllData.setCardNum(full_card_num.substring(full_card_num.length-4, full_card_num.length));
    creditCardAllData.setNameOnCard(basicInfo.get("nameOnCard"));
    creditCardAllData.setOpenBank(basicInfo.get("creditOpenBank"));
    var basicInfoUrl="https://ebanks.bankofshanghai.com/pweb/CreditAcctInfoQry.do?_navigator=pcreditcard.cardactqry.CreditAcctInfoQry";
    //https://ebanks.bankofshanghai.com/pweb/welcome.do
    Thread.sleep(1000);
    var  basic_info= ajax_get(basicInfoUrl);
    storeDataToFile(context,basic_info, creditCardNum+"_basic_info.html");
    var doc = Jsoup.parse(basic_info);
    try {
        var html = doc.select(".errors_def").html();
        if (html.contains("未持有我行信用卡")) {
            logger.info("无信用卡信息，停止抓取信用卡");
            return;
        }
    } catch ( e) {
        statCaughtException(context, e);
        logger.info("BOSHBank taskKey=" + context.get(LUA_TASK_KEY) +"信用卡页面解析失败");
    }
    var credit_limit ="";
    try {
        credit_limit=doc.select("tr.trValue:nth-child(3) > td:nth-child(4)").get(0).text();
    } catch ( e) {
        statCaughtException(context, e);
        // TODO: handle exception
        logger.info("BOSHBank taskKey=" + context.get(LUA_TASK_KEY) +"额度信息页面解析失败，停止抓取基本信息");
        return;
    }
    var balance=doc.select("tr.trValue:nth-child(4) > td:nth-child(4)").get(0).text();
    var cashBalance=doc.select("tr.trValue:nth-child(5) > td:nth-child(4)").get(0).text();

    var usd_credit_limit=doc.select("tr.trValue:nth-child(3) > td:nth-child(5)").get(0).text();
    var usd_balance=doc.select("tr.trValue:nth-child(4) > td:nth-child(5)").get(0).text();
    var usd_cash_limit=doc.select("tr.trValue:nth-child(5) > td:nth-child(5)").get(0).text();
    usdCreditLimitInfoMap.put(basicInfoUsdBalance, usd_balance);
    usdCreditLimitInfoMap.put(basicInfoUsdCashLimit, usd_cash_limit);
    usdCreditLimitInfoMap.put(basicInfoUsdCreditLimit, usd_credit_limit);

    //获取账单日  //TODO 页面已经改变
    billDate=doc.select("tr.trValue:nth-child(15) > td:nth-child(4)").get(0).text();
    //还款日
    payMentDate=doc.select("tr.trValue:nth-child(12) > td:nth-child(4)").get(0).text();
    var cash_balance=CreditResultUtil.StringToBigDecimal(cashBalance);
    //BigDecimal cash_limit=CreditResultUtil.StringToBigDecimal(credit_limit).divide(new BigDecimal("2"));
    creditCardAllData.setCardId(UUID.randomUUID().toString());
    creditCardAllData.setCardType("信用卡");
    creditCardAllData.setBankName("上海银行");
    creditCardAllData.setBalance(CreditResultUtil.StringToBigDecimal(balance));
    creditCardAllData.setCashBalance(cash_balance);
    creditCardAllData.setCreditLimit(CreditResultUtil.StringToBigDecimal(credit_limit));
    creditCardAllData.setCashLimit(null);
}
/**
 * 获取未结账单的账单月份
 */
function getUndoneBillMonthAndDate(){
    var billDay=0;
    var day="01";
    if (billDate.length>2 && billDate!=null) {
        day = billDate.substring(billDate.length-2,billDate.length);
        billDay=Integer.parseInt(day);
    }
    var calendar=Calendar.getInstance();
    var currentDay = calendar.get(Calendar.DAY_OF_MONTH);
    var dateFormat=new SimpleDateFormat("yyyy-MM");
    var time=new Array(2);
    var billMonth="";
    if (currentDay>billDay) {
        calendar.add(Calendar.MONTH,+1);
        billMonth=dateFormat.format(calendar.getTime());
    }else {
        billMonth=dateFormat.format(calendar.getTime());
    }
    time[0]=billMonth;
    time[1]=billMonth+"-"+day;
    return time;

}


/**
 * 抓取未结账单
 * @param creditCardAllData
 * @throws InterruptedException
 */
function crawlUndoneBill( creditCardAllData) {
    var billAllData =new BillAllData();
    billAllData.setBankName("上海银行");
    billAllData.setBillId(UUID.randomUUID().toString());
    billAllData.setBillType("UNDONE");
    var billMonthAndDate = getUndoneBillMonthAndDate();
    billAllData.setBillMonth(billMonthAndDate[0]);
    billAllData.setBillDate(yyyy_MM_dd_PARSER.parse(billMonthAndDate[1]));
    billAllData.setPaymentDueDate(null);//从账户信息页面取出
    billAllData.setCreditLimit(creditCardAllData.getCreditLimit());
    billAllData.setCashLimit(null);

    var usd_cash_limit = usdCreditLimitInfoMap.get(basicInfoUsdCashLimit);
    var usd_credit_limit=usdCreditLimitInfoMap.get(basicInfoUsdCreditLimit);
    billAllData.setUsdCashLimit(null);
    billAllData.setUsdCreditLimit(CreditResultUtil.StringToBigDecimal(usd_credit_limit));

    billAllData.setInterest(null);
    billAllData.setUsdInterest(null);
    billAllData.setUsdLastBalance(null);
    billAllData.setUsdLastPayment(null);
    billAllData.setUsdMinPayment(null);
    billAllData.setUsdNewBalance(null);
    billAllData.setUsdNewCharges(null);

    var bills = creditCardAllData.getBills();
    if (bills.size()>0) {
        billAllData.setLastBalance(bills.get(bills.size()-1).getNewBalance());
        billAllData.setNewBalance(bills.get(bills.size()-1).getNewBalance());
    }
    if (bills.size()==0) {
        billAllData.setNewBalance(null);
        billAllData.setLastBalance(null);
    }
    logger.info("请求未出账单的查询页面");
    var undoneUrl="https://ebanks.bankofshanghai.com/pweb/CreditBillInQueryPre.do?_navigator=pcreditcard.creditpaymgmt.BillInQry";
    var undoneBillOne = ajax_get(undoneUrl);
    storeDataToFile(context,undoneBillOne, "queryUndoneBill.txt");
    var doc = Jsoup.parse(undoneBillOne);
    //先判断  查询中，请稍后 如果有证明就是有数据可以继续请求
    var map=new LinkedHashMap();
    var elements = doc.select("body>input");
    for each(var element in elements) {
        var name = element.attr("name");
        var value=element.attr("value");
        map.put(name, value);
    }
    map.put("CRFlag", "Cs");
    map.put("Code", "CNY");//暂定为人民币消费的时候
    var url="https://ebanks.bankofshanghai.com/pweb/CreditBillInQuery.do";
    logger.info("BOSHBank taskKey=" + context.get(LUA_TASK_KEY)+"获取未出账单第一页");
    var pageDetailOne = ajax_post(url, map);
    storeDataToFile(context,pageDetailOne, "undone_shopping_sheets_"+billDetailNum+".html");
    billDetailNum++;
    var document = Jsoup.parse(pageDetailOne);
    var undoneFlag=null;
    try {
        undoneFlag= document.select( "#listTable > tbody:nth-child(2) > tr:nth-child(2) > td:nth-child(1)").get(0).text();
    } catch ( e) {
        statCaughtException(context, e);
        logger.info("未出账单页面解析失败，停止抓取");
        return;
    }
    if (undoneFlag.equals("查询无记录")) {
        logger.info("未出账单没有记录，停止抓取");
        return;
    }

    var currecy="CNY";
    parseUndoneInfo(billAllData, pageDetailOne,currecy);
    var pageOneDoc = Jsoup.parse(pageDetailOne);
    var pageNumStr = pageOneDoc.select(".pagesbutton").html();
    pageNumStr=pageNumStr.split("共")[1];
    pageNumStr=pageNumStr.substring(0, 1);
    var pageNum = Integer.parseInt(pageNumStr);
    var elements2 = pageOneDoc.select("body>input");
    for each(var element in elements2) {
        var name = element.attr("name");
        var value=element.attr("value");
        map.put(name, value);
    }
    map.put("currentIndex", 10+"");
    for(var i=1;i<pageNum;i++){
        var currentIndex=10;
        currentIndex=currentIndex*i;
        Thread.sleep(1000);
        map.put("currentIndex",Integer.toString(currentIndex));
        logger.info("BOSHBank taskKey=" + context.get(LUA_TASK_KEY) +"获取未出账单第"+(i+1)+"页");
        var html = ajax_post(url, map);
        storeDataToFile(context,html, "undone_shopping_sheets_"+billDetailNum+".html");
        billDetailNum++;
        parseUndoneInfo(billAllData, html,currecy);
    }
    logger.info("开始抓取未出美元账单");
    crawlUndoneUsdBill(billAllData);
    creditCardAllData.getBills().add(billAllData);
    //然后获取相关数据取post请求获得数据
}
/**
 * 美元未出账单第一页数据
 * @param billAllData
 * @throws InterruptedException
 */
function crawlUndoneUsdBill(billAllData) {
    var param=new LinkedHashMap();
    param.put("Code", "USD");
    param.put("CRFlag", "C");
    param.put("FlagCompare", "0");
    param.put("flag", "0");
    param.put("flag2", "0");
    param.put("flag3", "0");
    param.put("flag4", "0");
    param.put("listTable2sort3", "0");
    param.put("listTable2sort4", "0");
    param.put("listTable2sort5", "0");
    param.put("listTable2sort6", "0");
    var url="https://ebanks.bankofshanghai.com/pweb/CreditBillInQuery.do";
    logger.info("请求未出美元账单第一页");
    var usdPageOne = ajax_post(url, param);
    storeDataToFile(context,usdPageOne, "undone_usd_shopping_sheets_"+billDetailNum+".txt");
    billDetailNum++;
    var document = Jsoup.parse(usdPageOne);
    var undoneFlag=null;
    try {
        undoneFlag= document.select( "#listTable > tbody:nth-child(2) > tr:nth-child(2) > td:nth-child(1)").get(0).text();
    } catch ( e) {
         statCaughtException(context, e);
        logger.info("未出账单美元页面解析失败，停止抓取");
        return;
    }
    if (undoneFlag.equals("查询无记录")) {
        logger.info("未出账单美元信息没有记录，停止抓取");
        return;
    }
    logger.info("taskkey={}抓取未出账单美元信息",context.get(LUA_TASK_KEY));
    var currecy="USD";
    //这里故意出错，如果美元账单有问题可以暴漏出来
    parseUndoneInfo(billAllData, usdPageOne, currecy);

    var pageNumStr = document.select(".pagesbutton").html();
    pageNumStr=pageNumStr.split("共")[1];
    pageNumStr=pageNumStr.substring(0, 1);
    var pageNum = Integer.parseInt(pageNumStr);
    var elements2 = document.select("input");
    for each(var element in elements2) {
        var name = element.attr("name");
        var value=element.attr("value");
        param.put(name, value);
    }
    param.put("currentIndex", 10+"");
    logger.info("循环抓取美元未出账单多页");
    for(var i=1;i<pageNum;i++){
        var currentIndex=10;
        currentIndex=currentIndex*i;
        Thread.sleep(1000);
        param.put("currentIndex",Integer.toString(currentIndex));
        logger.info("BOSHBank taskKey=" + context.get(LUA_TASK_KEY) +"获取未出账单第"+(i+1)+"页");
        var html = ajax_post(url, param);
        storeDataToFile(context,html, "undone_usd_shopping_sheets_"+billDetailNum+".txt");
        billDetailNum++;
        parseUndoneInfo(billAllData, html,currecy);
    }
}





/**
 * 解析未结账单的详情
 * @param billAllData
 * @param currecy
 */
function parseUndoneInfo( billAllData ,undoneBillPage,currecy){
    logger.info("BOSHBank taskKey=" + context.get(LUA_TASK_KEY) + "正在解析未结账单详情页面");
    var doc = Jsoup.parse(undoneBillPage);
    var elements = doc.select("tr.trValue");
    if (elements.isEmpty()) {
        logger.info("BOSHBank taskKey=" + context.get(LUA_TASK_KEY) + "页面无数据，停止解析");
        return ;
    }
    var shopping_sheets = billAllData.getShoppingSheets();
    var order_index=shopping_sheets.size()+1;
    for each(var element in elements) {
        var expense=new Expense();
        expense.setNameOnOppositeCard("");
        expense.setOppositeBank("");
        expense.setOppositeCardNo("");
        expense.setRemark("");
        expense.setTransAddr("");
        expense.setTransChannel("");
        expense.setTransMethod("");

        var trans_date = element.select("td:nth-child(1)").get(0).text()+" 00:00:00";
        var post_date = element.select("td:nth-child(2)").get(0).text();
        var description = element.select("td:nth-child(3)").get(0).text();
        var amount_money = element.select("td:nth-child(4)").get(0).text();//这里要处理
        var card_num = element.select("td:nth-child(5)").get(0).text();

        var currency_type=CreditResultUtil.convertCurr(currecy);
        if(StringUtils.isBlank(currency_type)||currency_type.trim().length==0||currency_type.contains("其他")){
            currency_type="CNY";
        }
        expense.setCurrencyType(currency_type);
        expense.setId(UUID.randomUUID().toString());
        expense.setCategory(CategoryUtil.getCreditCategory("SHANGHAI", description,amount_money));
        if (amount_money.contains("-")) {//转入
            amount_money="-"+amount_money.split("-")[0];
        }
        if (amount_money.contains("+")) {//转入
            amount_money=amount_money.split("+")[0];
            if (currecy.equals("CNY")) {
                var new_charges = billAllData.getNewCharges();
                if(new_charges==null) {
                    new_charges = new BigDecimal("0");
                }
                billAllData.setNewCharges(new_charges.add(CreditResultUtil.StringToBigDecimal(amount_money)));//新增款额等于所有支出
            }
            if (currecy.contains("USD")) {
                var usd_new_charges = billAllData.getUsdNewCharges();
                if (usd_new_charges!=null) {
                    billAllData.setUsdNewCharges(usd_new_charges.add(CreditResultUtil.StringToBigDecimal(amount_money)));
                }else{
                    usd_new_charges=new BigDecimal("0");
                    billAllData.setUsdNewCharges(usd_new_charges.add(CreditResultUtil.StringToBigDecimal(amount_money)));
                }
            }
        }
        expense.setAmountMoney(CreditResultUtil.StringToBigDecimal(amount_money));

        var shangqinewBalance = billAllData.getNewBalance();
        if(shangqinewBalance==null || shangqinewBalance == undefined) {
            shangqinewBalance = new BigDecimal("0");
        }
        billAllData.setNewBalance(shangqinewBalance.add(expense.getAmountMoney()));//未出账单的new_balance等于 上期的newbalance+所有
        if (description.contains("还款")) {
            if (currecy.contains("CNY")) {
                var lastPayment=billAllData.getLastPayment();
                if(lastPayment==null) {
                    lastPayment = new BigDecimal("0");
                }
                billAllData.setLastPayment(lastPayment.add(expense.getAmountMoney()));//未出账单的last_payment等于本期的所有还款金额
            }
            if (currecy.contains("USD")) {
                var usd_last_payment = billAllData.getUsdLastPayment();
                if (usd_last_payment!=null) {
                    //billAllData.setUsdNewCharges(usd_new_charges.add(CreditResultUtil.StringToBigDecimal(amount_money)));
                    billAllData.setUsdLastPayment(usd_last_payment.add(expense.getAmountMoney()));//未出账单的last_payment等于本期的所有还款金额
                }else{
                    usd_last_payment=new BigDecimal("0");
                    billAllData.setUsdNewCharges(usd_last_payment.add(CreditResultUtil.StringToBigDecimal(amount_money)));
                }
            }
        }
        expense.setTransDate(yyyy_MM_dd_HH_mm_ss_PARSER.parse(trans_date));
        expense.setCardNum(card_num);
        expense.setOrderIndex(order_index);
        order_index++;
        expense.setDescription(description);

        expense.setPostDate(yyyy_MM_dd_PARSER.parse(post_date));
        shopping_sheets.add(expense);
    }
}

/**
 * 借记卡 返回月份
 *
 * @param dateStr
 *            formatDate('20170507')
 * @return 2017-05-07
 */
function formatMonth(dateStr) {
    dateStr = RegexUtils.GetText(dateStr, "(\\d+)");
    var d = null;
    try {
        d = DateUtils.parseDate(dateStr, "yyyyMMdd");
    } catch ( e) {
        statCaughtException(context, e);
        logger.error("解析日期格式出错" + dateStr, e);
    }
    dateStr = DateFormatUtils.format(d, "yyyy-MM");
    return dateStr;
}

/**
 * 读取 office 2003 excel
 *
 * @throws IOException
 * @throws FileNotFoundException
 */
function read2003Excel(file)  {
    var list = new LinkedList();
    var hwb = new HSSFWorkbook(new FileInputStream(file));
    var sheet = hwb.getSheetAt(0);
    var value = null;
    var row = null;
    var cell = null;
    var counter = 0;
    for (var i = sheet.getFirstRowNum(); counter < sheet.getPhysicalNumberOfRows(); i++) {
        row = sheet.getRow(i);
        if (row == null) {
            continue;
        } else {
            counter++;
        }
        var linked = new LinkedList();
        for (var j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
            cell = row.getCell(j);
            if (cell == null) {
                linked.add("");
            } else {
                linked.add(cell.toString());
            }

        }
        list.add(linked);
    }
    return list;
}



/**
 * --------------------业务抓取方法-----------------------
 * ------------------------end---------------------------
 */

/**
 * ----------------------lua方法-------------------------
 * -----------------------start--------------------------
 */



var luaFuncs = {
    /**
     * 输入用户名和密码方法二
     * @param username
     * @param password
     * @param type
     * @returns {*}
     */
    inputUPAndGetOperationResult: function (username, password) {
        var map = new LinkedHashMap();
        map.put("method", "inputUPAndGetOperationResult");
        map.put("username", username);
        map.put("password", password);
        return sendAndReceive(map)
    },
    /**
     * 输入用户名 和密码
     * @param username
     * @param password
     * @return
     */
    loginUsernameAndPassword: function (username, password) {
        var map = new LinkedHashMap();
        map.put("method", "loginUsernameAndPassword");
        map.put("username", username);
        map.put("password", password);
        return sendAndReceive(map);
    },
    /**
     * 点击登录按钮  同时检擦检查登录是否成功
     * @param string
     * @return
     */
    loginAndCheck: function (butttonId) {
        var map = new LinkedHashMap();
        map.put("method", "loginAndCheck");
        map.put("butttonId", butttonId);
        return sendAndReceive(map);
    },


    /**
     * 截取当前屏幕的状态
     * @return
     */
    getScreenShots: function () {
        var map = new LinkedHashMap();
        map.put("method", "getScreenShots");
        return sendAndReceive(map);
    },


    /**
     * 在hide情况下获取验证码图片
     * @param id
     * @return
     */
    getImgByIdOnHide: function (id) {
        var map = new LinkedHashMap();
        map.put("method", "getImgByIdOnHide");
        return sendAndReceive(map);
    },


    /**
     * 检查是否需要短信验证
     * @return
     */
    smsCheck: function () {
        var map = new LinkedHashMap();
        map.put("method", "smsCheck");
        return sendAndReceive(map);
    },
    /**
     * 检查当前页面是否是密码过于简单需要重置的页面
     * @return
     */
    simplePasswordCheck: function () {
        var map = new LinkedHashMap();
        map.put("method", "simplePasswordCheck");
        return sendAndReceive(map);
    },


    getHtmlGb2312: function () {
        var map = new LinkedHashMap();
        map.put("method", "getHtmlGb2312");
        return sendAndReceive(map);
    },

    /**
     * 进入主页后判断是之后是主页
     * @return
     */
    judgeMainPage: function () {
        var map = new LinkedHashMap();
        map.put("method", "judgeMainPage");
        return sendAndReceive(map);
    },
    /**
     * 根据taskkey复制文件path到与当前文件同目录下的文件夹下
     * @param path
     * @param taskKey
     * @param name
     * @return
     */
    copyFile: function (path, taskKey, name) {
        var map = new LinkedHashMap();
        map.put("method", "copyFile");
        map.put("path", path);
        map.put("name", name);
        map.put("taskkey", taskKey);
        return sendAndReceive(map);

    },


    /**
     * 提交短信验证码并且判断是否正确
     * @param vcode
     * @return
     */
    submitSmsAndCheck: function (vcode) {
        var map = new LinkedHashMap();
        map.put("method", "submitSmsAndCheck");
        map.put("sms", vcode);
        return sendAndReceive(map);


    },
    /**
     * ajax获取文件下载的方法
     * @return 是否登录成功的标志
     * @throws Exception
     */
    ajaxPostFile:function(url, param) {
        var datas="";
        var entrySet = param.entrySet();
        for each(var entry in entrySet) {
            var key = entry.getKey();
            var value=entry.getValue();
            datas=datas+key+"="+value+"&";
        }
        var map=new LinkedHashMap();
        map.put("method", "ajaxPostFile");
        map.put("url",url);
        map.put("data", datas);
        return sendAndReceive(map);
    },
    exitPulignProcess:function () {
        var map=new LinkedHashMap();
        map.put("method", "exitPulignProcess");
        return sendAndReceive(map);
    },
    checkControlAvailable:function(){
        var map = new HashMap();
        map.put("method","checkControlAvailable");
        return sendAndReceive(map)
    },
    //点击登录
    clickById:function(id) {
    var map = new LinkedHashMap();
    map.put("method", "clickById");
    map.put("id",id);
    return sendAndReceive(map);
},
    setSizeAndShow: function () {
        var map = new LinkedHashMap();
        map.put("method", "setSizeAndShow");
        return sendAndReceive(map);
    }

}

/**
 * -----------------------lua方法------------------------
 * ------------------------end---------------------------
 */
